package org.xs.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.xs.entity.Video;
import org.xs.entity.VideoOrder;
import org.xs.service.VideoService;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("api/v1/video_order")
@RefreshScope
public class OrderController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private VideoService videoService;

    @Value("${video.title}")
    private String videoTitle;

    @RequestMapping("/save")
    public Object save(int videoId) {
        // 最原始的多服务调用： 问题： ip 端口写死，不灵活， 无法负载均衡
        // ResponseEntity<Video> videoResponseEntity = restTemplate.getForEntity("http://192.168.2.113:9000/api/v1/video/find_by_id?videoId=" + videoId, Video.class);
        // Video video = videoResponseEntity.getBody();

        // 使用 nacos 获取 服务的 地址和端口号 实现 服务互相调用
//        List<ServiceInstance> instanceList = discoveryClient.getInstances("xdclass-video-service");
//        // 因为是单节点服务，所以取第一个
//        ServiceInstance serviceInstance = instanceList.get(0);
//        Video video = restTemplate.getForObject("http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/api/v1/video/find_by_id?videoId=" + videoId, Video.class);

        // 使用 ribbon 负载均衡之后的写法: ribbon  可以自动吧服务（xdclass-video-service） 解析成 服务的地址 并进行负载均衡
        // Video video = restTemplate.getForObject("http://xdclass-video-service/api/v1/video/find_by_id?videoId=" + videoId, Video.class);

        //使用Open  Feign 进行负载均衡的写法  -----> 跟调用本地方法一样
        Video video = videoService.findById(videoId);

        VideoOrder videoOrder = new VideoOrder();
        videoOrder.setVideoId(video.getId());
        videoOrder.setVideoTitle(video.getTitle());
        videoOrder.setCreateTime(new Date());
        videoOrder.setServerInfo(video.getServerInfo());
        // 测试 nacos 配置中心的动态配置
        videoOrder.setOutTradeNo(videoTitle);
        return videoOrder;
    }

    @RequestMapping("list")
    public Object list(HttpServletRequest request){
        Map<String, Object> map = new HashMap<>();
        map.put("title", "test title");
        map.put("code", "0");
        map.put("server", request.getServerPort());

        return map;
    }
}
